package com.Cfeng.XiaohuanChat.service.impl;

import com.Cfeng.XiaohuanChat.entity.UserNote;
import com.Cfeng.XiaohuanChat.repository.UserNoteRepository;
import com.Cfeng.XiaohuanChat.service.UserNoteService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.List;
import java.util.Objects;

/**
 * @author Cfeng
 * @date 2022/8/12
 */

@Service
@RequiredArgsConstructor
public class UserNoteServiceImpl implements UserNoteService {

    private final UserNoteRepository userNoteRepository;


    @Override
    public void addNote(UserNote note) {
        userNoteRepository.save(note);
    }

    @Override
    public UserNote getNote(String noteTitle) {
        return userNoteRepository.findByNoteTitle(noteTitle);
    }

    @Override
    public UserNote getNote(Long id) {
        return userNoteRepository.findById(id).get();
    }

    @Override
    public List<UserNote> getNotes() {
        return userNoteRepository.findAll();
    }

    @Override
    @Transactional
    public void removeNote(String noteTitle) {
        userNoteRepository.deleteByNoteTitle(noteTitle);
    }

    @Override
    //可能抛出空指针异常
    public void updateNote(UserNote note) throws Exception {
        //save方法需要将该note查询出来之后再null值赋值,只有ID不变，title可以变化
        UserNote originNote = userNoteRepository.findById(note.getId()).get();
        //反射方式获取现在对象的属性
        Field[] fields = note.getClass().getDeclaredFields();
        for(Field field : fields) {
            field.setAccessible(true);
            //获取属性值，空则赋值
            if(Objects.isNull(field.get(note))) {
                //空字段属性赋值
                field.set(note,field.get(originNote));
            }
        }
        userNoteRepository.save(note);
    }
}
